package com.hyhy.hycloud.uaa.controller;

import com.hyhy.hycloud.commons.dto.InvokeResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.session.Session;
import org.springframework.session.SessionRepository;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 会话存储REST API
 *
 * @author Xuegui Yuan
 * @date 2018-09-19
 */
@RequestMapping("/session")
@RestController
public class SessionController {

    @Autowired
    SessionRepository sessionRepository;

    @PostMapping("/attrs")
    public InvokeResult<Object> setSessionAttr(@RequestParam(name = "key") String key,
                                               @RequestParam(name = "value") String value,
                                               HttpServletRequest request) {
        request.getSession().setAttribute(key, value);
        return InvokeResult.success(request.getSession().getAttribute(key));
    }

    @GetMapping("/attrs")
    public InvokeResult<Object> getSessionAttr(@RequestParam(name = "key") String key,
                                               HttpServletRequest request) {
        return InvokeResult.success(request.getSession().getAttribute(key));
    }

    @GetMapping("/{sessionId}")
    public InvokeResult<Object> getPrincipalBySessionId(@PathVariable(name = "sessionId") String sessionId) {
        Session session = sessionRepository.findById(sessionId);
        SecurityContext securityContext = session.getAttribute("SPRING_SECURITY_CONTEXT");
        return InvokeResult.success(securityContext.getAuthentication().getPrincipal());
    }
}
